//
//  WBComposeTextView.swift
//  WBWeiBo
//
//  Created by 王斌 on 16/7/18.
//  Copyright © 2016年 王斌. All rights reserved.
//

import UIKit

//  实时看到xib设置的属性
@IBDesignable
class WBComposeTextView: UITextView {

    // MARK: - 懒加载控件
    private lazy var placeHolderLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "冰是睡着的水 ~ 愿载风尘,吹走那傲慢与偏见"
        
        // 多行显示
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        
        return label
    }()
    
    
    //  占位文字
    //  给xib添加设置属性
    @IBInspectable var placeHolder:String?{
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    
    
    //  重写font
    override var font :UIFont?{
        
        didSet{
            //  如果外界传入nil 直接返回
            if font == nil{
                return
            }
            placeHolderLabel.font = font
        }
    }
    
    
    //  重写text
    override var text:String?{
        didSet{
            placeHolderLabel.hidden = hasText()
        }
    }
    
    
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //  添加控件设置约束
    private func setupUI(){
        
        //  监听UITextView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        addSubview(placeHolderLabel)
        
        //  使用手写布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
    }
    
    //  MARK : -- 监听文字改变的方法
    @objc private func textChange(){
        
        //  判断有内容的话就隐藏占位label
        placeHolderLabel.hidden = self.hasText()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}














